#include "MapObstacle.h"
#include "Landscape.h"

mtBEGIN(MapObstacleDef)
	mtCONSTRUCTOR();
mtEND

mtBEGIN(MapObstacle)
	mtBASE(ECS::Component);
	mtMETHOD(onStart);
	mtCONSTRUCTOR();
	mtMETHOD(initWith);
mtEND

void MapObstacle::onSetTransform( const ECS::Vec2<float>& pos, float ang )
{
	auto newPos = ECS::Vec2<int>(pos);
	if (newPos != _position)
	{
		_map->setPassable(_position.x, _position.y, true);
		_map->setUserData(_position.x, _position.y, nullptr);
		_position = newPos;
		_map->setPassable(_position.x, _position.y, false);
		_map->setUserData(_position.x, _position.y, this);
	}
}

MapObstacle::MapObstacle()
{

}

bool MapObstacle::initWith( MapObstacleDef* def )
{
	return true;
}

void MapObstacle::onStart()
{
	_map = Landscape::getInstance()->getMap();
	_tClient = getComponent<Transform>()->createClient([this](const ECS::Vec2<float>& pos, float ang) { onSetTransform(pos, ang); });
}

void MapObstacle::onDestroyed()
{
}

void MapObstacle::onEnabled( bool enabled )
{
	if (!enabled)
	{
		_map->setPassable(_position.x, _position.y, true);
		_map->setUserData(_position.x, _position.y, nullptr);
	}
	else
	{
		_map->setPassable(_position.x, _position.y, false);
		_map->setUserData(_position.x, _position.y, this);
	}
}

MapObstacle::~MapObstacle()
{
	_map->setPassable(_position.x, _position.y, true);
	_map->setUserData(_position.x, _position.y, nullptr);
}
